package com.wunu.smartlock1.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;

import com.google.gson.Gson;
import com.wunu.smartlock1.R;
import com.wunu.smartlock1.net.NetComponent;
import com.wunu.smartlock1.net.api.LockTempKeyApi;
import com.wunu.smartlock1.net.param.SubmitTempKeyParam;
import com.wunu.smartlock1.net.response.ApiNormalResponse;
import com.wunu.smartlock1.net.response.ApiSimpleResponse;
import com.wunu.smartlock1.net.response.LockItem;
import com.wunu.smartlock1.net.response.TempKey;
import com.wunu.smartlock1.util.CustomDatePicker;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import retrofit2.Call;
/**
 * Created by admin on 2018/4/21.
 */

public class TemporyLockActivity extends AppCompatActivity{
    LockTempKeyApi service = NetComponent.getRetrofit().create(LockTempKeyApi.class);
    String toast;
    TextView temporaryKeyTextView;//临时密码
    TextView temporaryNameTextView;//名称
    TextView dateTextView;//生效时间
    TextView timeTextView;//生效时间
    TextView validTimeValueTextView;//有效时长
    TextView validTermsTextView;//有效次数

    SubmitTempKeyParam params = new SubmitTempKeyParam();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);

    CustomDatePicker temps;
    Button sendSMS;
    LockItem lockItem;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            System.out.println("msg----------------------->:"+msg);
            System.out.println("obj->"+msg.getData());
            switch (msg.what){
                case 0://临时密钥
                    ApiNormalResponse<TempKey> tempKeyResp = (ApiNormalResponse<TempKey>) msg.obj;
                    if(tempKeyResp.getCode() == 0 && tempKeyResp.getData().getCode() == 200){
                        params.setTempKeyId(Long.valueOf(tempKeyResp.getData().getData().getTempKeyId()));
                        temporaryKeyTextView.setText(String.valueOf(tempKeyResp.getData().getData().getTempKeyCode()));
                    }else{
                        Toast.makeText(TemporyLockActivity.this, "获取临时密钥失败!", Toast.LENGTH_SHORT).show();
                        TemporyLockActivity.this.finish();
                    }
                    break;
                case 2:
                    ApiSimpleResponse respSms = (ApiSimpleResponse)msg.obj;
                    System.out.println("obj:"+respSms);
                    if (respSms == null || respSms.getCode() == -1){
                        Toast.makeText(TemporyLockActivity.this, "发送失败"+respSms, Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(TemporyLockActivity.this, "发送成功" + respSms, Toast.LENGTH_SHORT).show();
                    }
                    break;
            }

        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.smartlock_lock_temporylock);
        //生效时间
        dateTextView = findViewById(R.id.dateTextView);
        timeTextView = findViewById(R.id.timeTextView);
        validTimeValueTextView = findViewById(R.id.validTimeValueTextView);
        validTermsTextView = findViewById(R.id.validTermsTextView);

        temporaryKeyTextView = findViewById(R.id.temporaryKeyTextView);
        temporaryNameTextView = findViewById(R.id.temporaryNameTextView);

        String nows = sdf.format(new Date());
        dateTextView.setText(nows.substring(0,10));
        timeTextView.setText(nows.substring(11));

        params.setStartTime(nows);
        params.setValidCount(1);//默认1次
        params.setValidTime(5*6*60);//默认设置的0.5小时
        //取得从上一个Activity当中传递过来的Intent对象
        Intent intent = getIntent();
        //从Intent当中根据key取得value
        if (intent != null) {
            String value = intent.getStringExtra("lockItem");
            lockItem = new Gson().fromJson(value, LockItem.class);
            if (lockItem == null) {
                System.out.println("未获取到页面传值，失败!");
                Toast.makeText(TemporyLockActivity.this, "未获取到页面传值，失败!", Toast.LENGTH_SHORT).show();
                TemporyLockActivity.this.finish();
            }
        }
        temporaryNameTextView.setText("名称:" + lockItem.getName());
        final int lockId = lockItem.getId();
        //获取临时密钥
        new Thread() {
            @Override
            public void run() {
                LockTempKeyApi service = NetComponent.getRetrofit().create(LockTempKeyApi.class);
                Call<ApiNormalResponse<TempKey>> call = service.genTempKey(lockId);
                try {
                    ApiNormalResponse<TempKey> resp = call.execute().body();
                    System.out.println(resp);
                    Message msg = handler.obtainMessage();
                    msg.obj = resp;
                    msg.what = 0;//处理临时密钥
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

        initDatePicker();

        //给button按钮绑定单击事件，设置完参数后跳转到首页
        sendSMS = findViewById(R.id.sendSMS);//发送临时密码
        sendSMS.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputTitleDialog();
            }
        });

        timeTextView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                System.out.println("--1---------o");
                String now = sdf.format(new Date());
                temps.show(now);
            }
        });
        dateTextView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                System.out.println("---2--------o");
                String now = sdf.format(new Date());
                temps.show(now);
            }
        });
        validTimeValueTextView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                System.out.println("---3--------o");
                inputValidTimeText();
            }
        });
        validTermsTextView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                System.out.println("---4--------o");
                inputValidTermText();
            }
        });
    }
    public void inputValidTimeText(){
        final EditText inputServer = new EditText(this);
        inputServer.setFocusable(true);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("有效时长，单位为秒").setView(inputServer).setNegativeButton(
                getString(R.string.smartlock_cancel), null);
        builder.setPositiveButton(getString(R.string.smartlock_ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String validTime = inputServer.getText().toString();
                        System.out.println(validTime+"----");
                        validTimeValueTextView.setText(String.format("%.2f",Double.parseDouble(validTime)/60/60)+"小时");
                        params.setValidTime(Integer.parseInt(validTime));
                    }
                });
        builder.show();
    }
    public void inputValidTermText(){
        final EditText inputServer = new EditText(this);
        inputServer.setFocusable(true);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("有效次数").setView(inputServer).setNegativeButton(
                getString(R.string.smartlock_cancel), null);
        builder.setPositiveButton(getString(R.string.smartlock_ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String validTerm = inputServer.getText().toString();
                        System.out.println(validTerm+"----有效次数");
                        validTermsTextView.setText(""+validTerm+"次");
                        params.setValidCount(Integer.parseInt(validTerm));
                    }
                });
        builder.show();
    }
    private void inputTitleDialog() {
        final EditText inputServer = new EditText(this);
        inputServer.setFocusable(true);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请输入手机号码").setView(inputServer).setNegativeButton(
                getString(R.string.smartlock_cancel), null);
        builder.setPositiveButton(getString(R.string.smartlock_ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        final String phone = inputServer.getText().toString();
                        System.out.println("phone:"+phone);
                        System.out.println("lockId:"+lockItem.getId());

                        System.out.println("sendSMS.setOnClickListener ");
                        //开线程加载数据
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                System.out.println("-------------------------->sendSMS begin");
                                params.setLockId(lockItem.getId());
                                params.setCc("86");
                                params.setPhone(phone);
                                System.out.println("临时密钥参数: "+params);
                                try{
                                    final LockTempKeyApi service = NetComponent.getRetrofit().create(LockTempKeyApi.class);
                                    Call<ApiSimpleResponse> call = service.submitTempKey(params);
                                    final ApiSimpleResponse resp = call.execute().body();
                                    System.out.println("resp: "+resp);

                                    // 判断锁是否绑定成功
                                    Message msg = handler.obtainMessage();
                                    msg.obj = resp;
                                    msg.what = 2;
                                    handler.sendMessage(msg);
                                } catch (Exception e) {
                                    System.out.println("锁绑定异常:" + e);
                                }
                            }
                        }.start();
                    }
                });
        builder.show();
    }

    private void initDatePicker() {
        String now = sdf.format(new Date());
        temps = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                System.out.println(time);
                dateTextView.setText(time.substring(0,10));
                timeTextView.setText(time.substring(11));
                params.setStartTime(time);
            }
        },  now,"2020-01-01 00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        temps.showSpecificTime(true); // 显示时和分
        temps.setIsLoop(true); // 允许循环滚动
    }

}
